# -*- coding: utf-8 -*-

import pickle

try:
    # Pytnon 3
    from socketserver import BaseRequestHandler
except ImportError:
    # Pytnon 2
    from SocketServer import BaseRequestHandler

class MsgUdpRequestHandler(BaseRequestHandler):
    """
    Accepts only jsonable string data
    And sends too...

    Reimplement _request_handle method!
    """

    def _request_handle(self, data):
        """
        @param data: simple object data
        @type: dict

        @return: python simple object data, picklable
        @rtype: mixed
        """
        raise NotImplementedError("Method _request_handle must be implemented in %s" % self.__class__.__name__)

    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]

        try:
            data = pickle.loads(data)
            data = self._request_handle(data)
            data = pickle.dumps(data, 2)
        except Exception as e:
            import traceback
            print("MsgUdpRequestHandler: %r\n%s" % (e, traceback.format_exc()))
            data = ""

        socket.sendto(data, self.client_address)
        return

    pass


RequestHandler = MsgUdpRequestHandler
